package com.example.springboot01.interceptor;

import com.example.springboot01.annotation.Permissions;
import com.example.springboot01.annotation.WithoutAuthorization;
import com.example.springboot01.constant.Constants;
import com.example.springboot01.model.TokenModel;
import com.example.springboot01.service.TokenManageService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * 自定义拦截器，校验用户身份
 * @author developer
 * @since 2022-5-17
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    TokenManageService tokenManageService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        //如果接口不需要token，直接返回
        if (method.getAnnotation(WithoutAuthorization.class) != null){
            return true;
        }

        // 从header中得到token
        String token = request.getHeader(Constants.TOKEN_NAME);

        // 如果token校验失败，则返回401错误消息
        if(!tokenManageService.checkToken(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //校验token的身份s是否可以访问对应的接口
        Permissions permissionAnnotation = method.getAnnotation(Permissions.class);
        if (permissionAnnotation != null){
            TokenModel tokenModel = tokenManageService.extractToken(token);
            if (tokenModel == null || StringUtils.isEmpty(tokenModel.getUserType())){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            //如果接口的角色和token用户角色不一致，返回403错误
            if (!permissionAnnotation.role().equals(tokenModel.getUserType())){
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return false;
            }
        }
        return true;
    }

}
